package com.uxsino.simo.collector.connections;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jcraft.jsch.SftpException;
import com.uxsino.commons.loganalyzer.nginx.NginxLogAnalyzer;
import com.uxsino.simo.connections.exception.SimoConnectionException;
import com.uxsino.simo.connections.exception.SimoQueryException;
import com.uxsino.simo.connections.target.SSHFileDownloadTarget;
import com.uxsino.simo.connections.target.TCPTarget;

public class SSHFileDownloadConnection extends AbstractSFTPConnection<SSHFileDownloadTarget> {

    private static Logger logger = LoggerFactory.getLogger(SSHFileDownloadConnection.class);

    protected String[] filePaths;

    protected String[] fileNames;

    protected String id;

    public SSHFileDownloadConnection() {
        super();
    }

    @Override
    public int connect(TCPTarget target) {
        //super.connect(target);
        initFileNameAndPath((SSHFileDownloadTarget) target);
        id = target.host + "_" + target.port + "_" + (new Date()).getTime();
        return super.connect(target);
    }

    @Override
    public Object execCmd(Object cmdPattern) throws SimoQueryException, SimoConnectionException {
        String cmdStr = (String) cmdPattern;

        try {
            for (int i = 0; i < filePaths.length; i++) {
                InputStream is = null;
                BufferedInputStream bis = null;
                BufferedOutputStream bos = null;

                try {
                    is = download(filePaths[i], fileNames[i]);
                    if (is == null) {
                        throw new SimoConnectionException("no connection valid.");
                    }
                    bis = new BufferedInputStream(is);
                    File outputFile = new File(id + fileNames[i]);
                    logger.info("download file absolute path {}", outputFile.getAbsolutePath());

                    bos = new BufferedOutputStream(new FileOutputStream(outputFile));
                    int readCount;
                    byte[] buffer = new byte[1024];
                    while ((readCount = bis.read(buffer)) > 0) {
                        bos.write(buffer, 0, readCount);
                    }
                }catch (Exception ee){
                    throw  ee;
                }finally {
                    try {
                        if(is !=null){
                            is.close();
                        }
                    }catch (Exception e){}
                    try {
                        if(bis !=null){
                            bis.close();
                        }
                    }catch (Exception e){}
                    try {
                        if(bos !=null){
                            bos.close();
                        }
                    }catch (Exception e){}

                }

            }
        } catch (IOException e) {
            logger.error("error execCmd", e);
            throw new SimoConnectionException("no connection valid.");
        }
        Object result = null;
        switch (cmdStr) {
        case "nginx_log_analysis":
            NginxLogAnalyzer analyzer = new NginxLogAnalyzer(id, fileNames);
            result = analyzer.getLogAnalysisReport();
            break;
        default:
            break;
        }

        return result;
    }

    @Override
    public int supportedFeatures() {
        return F_DOWNLOAD;
    }

    @Override
    public boolean upload(String remotePath, String fileName, InputStream fileToUpload) {
        return false;
    }

    @Override
    public InputStream download(String remotePath, String fileName) throws SimoConnectionException {
        try {
            channelSftp.cd(remotePath);
            return channelSftp.get(fileName);
        } catch (SftpException e) {
            logger.error("error download file, path {}, file name {} ", remotePath, fileName, e);
            throw new SimoConnectionException(e);
        }

    }

    protected void initFileNameAndPath(SSHFileDownloadTarget target) {
        filePaths = target.getFilePaths().split(",");
        fileNames = target.getFileNames().split(",");
        for (int i = 0; i < filePaths.length; i++) {
            filePaths[i] = filePaths[i].trim();
            fileNames[i] = fileNames[i].trim();
        }
    }

}
